package com.bizdk.generator.controller.gen;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bizdk.generator.common.page.PageResult;
import com.bizdk.generator.common.query.Query;
import com.bizdk.generator.common.utils.R;
import com.bizdk.generator.controller.SimpleController;
import com.bizdk.generator.entity.gen.Group;
import com.bizdk.generator.entity.gen.Template;
import com.bizdk.generator.service.GroupService;
import com.bizdk.generator.service.TemplateService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.Arrays;

/**
 * 项目名变更
 */
@AllArgsConstructor
@Controller
@RequestMapping("/gen/group")
public class GroupController extends SimpleController<GroupService, Group> {
    
    private TemplateService templateService;
    
    @Override
    protected String getPrefix() {
        return "gen/group";
    }
    
    @ResponseBody
    @RequestMapping("/page")
    public R<PageResult<Group>> page(@Valid Query query) {
        PageResult<Group> page = service.page(query);
        return R.ok(page);
    }
    
    @Override
    public ModelAndView edit(@PathVariable("id") Long id) {
        Group data = service.getById(id);
        ModelAndView modelAndView = super.edit(id);
        modelAndView.addObject("data", data);
        return modelAndView;
    }
    
    @ResponseBody
    @PostMapping("/save")
    public R<String> save(Group entity) {
        boolean flag = service.save(entity);
        return BooleanUtil.isTrue(flag) ? R.ok() : R.error();
    }
    
    @ResponseBody
    @PutMapping("/update")
    public R<String> update(@Valid Group entity) {
        service.updateById(entity);
        
        return R.ok();
    }
    
    @ResponseBody
    @PostMapping("/delete")
    public R<String> delete(Long[] ids) {
        for (Long id : ids) {
            LambdaQueryWrapper<Template> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Template::getGroupId, id);
            long count = templateService.count(wrapper);
            if (count > 0) {
                return R.error(id + ", 存在模板不能被删除");
            }
        }
        service.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}